import sys,struct,ctypes,pyaudio, math, random
from numpy import *
from numpy.fft import *

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 5000
RECORD_SECONDS = 150

p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
                channels = CHANNELS, 
                rate = RATE, 
                input = True)

stream_out = p.open(format = FORMAT,
        channels = CHANNELS,
        rate = RATE,
        output = True)

stream_out2 = p.open(format = FORMAT,
        channels = CHANNELS,
        rate = RATE,
        output = True)

def average(values):
    if len(values) == 0:
        return None
    return sum(values, 0.0) / len(values)


print "* recording"

ok = ''
sample = 0
temp_chunk = []
for i in range(0, RATE / chunk * RECORD_SECONDS ):

    data = stream.read(chunk)

    # make array
    audio_data  = fromstring(data, dtype=short)
    
    gg = 0
    ti = []
    audio = []
    out_audio = []

    # data refine
    for aa in audio_data:
        if gg%2 == 1:
            audio.append(aa)
        gg = gg + 1

    # initial 
    if len(temp_chunk)==0:
        temp_chunk = audio
        continue

    # moving average
    gg = len(audio)
    mov = 100
    audio = temp_chunk + audio 

    for uu in range(0,chunk/2):
        ti.append(average(audio[gg-mov:gg]))
        gg = gg + 1

    # for next step
    temp_chunk = ti
    
    # two channel
    for aa in range(0, len(ti)):
        out_audio.append(audio_data[aa*2])
        out_audio.append(ti[aa])

    # make audio format 
    out = ''
    for ad in out_audio:
        if ad > 32767:
            ad = 32767
        if ad < -32767:
            ad = -32767
        sample = struct.pack('h', ad)
        out = out + sample
    
    stream_out.write(out)


print "* done"

stream.stop_stream()
stream.close()
stream_out.stop_stream()
stream_out.close()
stream_out2.stop_stream()
stream_out2.close()
p.terminate()